<?php
namespace app\live\controller\sys_admin;
use app\live\model\LiveGoodsModel;
use app\live\model\LiveRoomModel;
use app\shop\model\OrderModel;
use think\Db;
use app\AdminController;
use app\member\model\UsersModel;
use app\shop\model\OrderGoodsModel;
use utils\Time;

/**
 * 微信设置
 * Class Index
 * @package app\store\controller
 */
class LiveRoom extends AdminController
{
	/*------------------------------------------------------ */
	//-- 优先执行
	/*------------------------------------------------------ */
	public function initialize(){
        parent::initialize();
        $this->Model = new LiveRoomModel();
    }

    /*------------------------------------------------------ */
    //--首页
    /*------------------------------------------------------ */
    public function index()
    {
        $this->getList(true);
        return $this->fetch('index');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false) {
        $this->assign("live_status", $this->Model->live_status);
        $where = [];
        $search['live_status'] = input('live_status','','trim');
        if (empty($search['live_status']) == false){
            $where[] = ['live_status','=',$search['live_status']];
        }
        $search['keyword'] = input('keyword','','trim');
        if (empty($search['keyword']) == false){
            if (is_numeric($search['keyword'])) {
                $where[] = ['anchor_user_id','=',$search['keyword']];
            } else {
                $where[] = ['name','like','%'.$search['keyword'].'%'];
            }
        }
        $this->sqlOrder = "start_time DESC";
        $data = $this->getPageList($this->Model,$where);
        $this->assign("data", $data);
        if ($runData == false){
            $data['content']= $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 添加直播间
    /*------------------------------------------------------ */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            $data['herald_time'] = strtotime($data['startTime']);
            $data['endTime'] = strtotime($data['endTime']);
            $anchor_user_id = $data['select_user'];
            unset($data['select_user']);
            $roomData['roomid'] = 0;
            $roomData['live_status'] = 102;
            $roomData['name'] = $data['name'];
            $roomData['herald_time'] = $data['herald_time'];
            $roomData['anchor_user_id'] = $anchor_user_id;
            $roomData['anchor_name'] = $data['anchor_name'];
            $roomData['cover_img'] = $data['cover_img'];
            $res = $this->Model->save($roomData);
            if ($res == false){
                return $this->error('写入数据库失败.');
            }
            return $this->success('添加成功.');
        }
        return $this->fetch('add');
    }
    /*------------------------------------------------------ */
    //-- 管理直播间商品
    /*------------------------------------------------------ */
    public function editGoods()
    {
        $id = input('id', 0, 'intval');
        $roomInfo = $this->Model->find($id);
        if (empty($roomInfo)){
            return $this->error('没有找到相关房间数据.');
        }
        $LiveGoodsModel = new LiveGoodsModel();
        if ($this->request->isPost()) {
            if ($roomInfo['live_status'] > 102){
                return $this->error('已结束的直播不能修改.');
            }
            $goods_ids = input('goods_ids');
            if (empty($goods_ids)){
                return $this->error('请选择直播商品.');
            }
            $lgwhere[] = ['goods_id','in',$goods_ids];
            $shop_goods_id = $LiveGoodsModel->where($lgwhere)->column('goods_id');
            $upData['goods_ids'] = join(',',$shop_goods_id);
            if ($roomInfo['goods_ids'] == $upData['goods_ids']){
                return $this->error('直播商品没有变化，无须修改.');
            }
            $res = $this->Model->where('id',$id)->update($upData);
            if ($res < 1){
                return $this->error('更新失败.');
            }
            $this->_log($id,'导入直播间商品：'.$upData['goods_ids']);
            return $this->success('修改直播商品成功', 'reload');
        }
        $roomInfo['goods_list'] = [];
        if (empty($roomInfo['goods_ids']) == false){

            $where[] = ['goods_id','in',$roomInfo['goods_ids']];
            $roomInfo['goods_list'] = $LiveGoodsModel->where($where)->select()->toArray();
            $this->assign('priceType',$LiveGoodsModel->priceType);
        }
        $this->assign('roomInfo',$roomInfo);
        return $this->fetch('edit_goods');
    }
    /*------------------------------------------------------ */
    //-- 显示详情
    /*------------------------------------------------------ */
    public function showInfo()
    {
        $id = input('id', 0, 'intval');
        $roomInfo = $this->Model->find($id);
        if (empty($roomInfo)){
            return $this->error('没有找到相关房间数据.');
        }
        $this->assign('roomInfo',$roomInfo);

        $status = null;
        if ($roomInfo['roomid'] != 0){
            $OrderGoodsModel = new OrderGoodsModel();
            $status = $OrderGoodsModel->where('roomid',$roomInfo['roomid'])->field('SUM(goods_number) as total_goods_number,goods_id,goods_name')->group('goods_id')->select();
        }
        $this->assign('status',$status);
        return $this->fetch('show_info');
    }
    /*------------------------------------------------------ */
    //-- 设置回播
    /*------------------------------------------------------ */
    public function setReplay(){
        $id = input('id', 0, 'intval');
        $toggle = input('toggle', '', 'trim');
        $roomData['is_replay'] = 0;
        if ($toggle == 'true'){
            $roomData['is_replay'] = 1;
        }
        $this->Model->where('id',$id)->update($roomData);
        return $this->success('修改成功.'.$toggle);
    }
    /*------------------------------------------------------ */
    //-- 设置是否显示
    /*------------------------------------------------------ */
    public function setIsShow(){
        $id = input('id', 0, 'intval');
        $toggle = input('toggle', '', 'trim');
        $roomData['is_show'] = 0;
        if ($toggle == 'true'){
            $roomData['is_show'] = 1;
        }
        $this->Model->where('id',$id)->update($roomData);
        return $this->success('修改成功.'.$toggle);
    }

    public function del()
    {
        $id = input('id',0,'intval');
        if ($id < 1){
            return $this->error('ID传参出错.');
        }
        $row = $this->Model->where('id',$id)->find();
        if (empty($row)){
            return $this->error('没有找到相关数据.');
        }
        $res = $this->Model->where('id',$id)->delete();
        if ($res < 1){
            return $this->error('删除失败.');
        }
        $this->_log($id,'删除直播间');
        return $this->success('删除成功.',url('index'));
    }

    /*------------------------------------------------------ */
    //-- 直播数据
    /*------------------------------------------------------ */
    public function statistics() {

        list($todayS, $todayE) = Time::today();

        // 订单总金额
        $all_live_money = Db::table('shop_order_info')->alias('o')
            ->join('shop_order_goods og', 'o.order_id = og.order_id')
            ->where('og.roomid', '>', 0)
            ->where('o.pay_status', 1)
            ->sum('o.order_amount');

        // 今日订单金额
        $today_pay_money = Db::table('shop_order_info')->alias('o')
            ->join('shop_order_goods og', 'o.order_id = og.order_id')
            ->where('og.roomid', '>', '0')
            ->whereBetweenTime('o.pay_time', $todayS, $todayE)
            ->sum('o.order_amount');

        // 今日订单数
        $today_order_nums = Db::table('shop_order_info')->alias('o')
            ->join('shop_order_goods og', 'o.order_id = og.order_id')
            ->where('og.roomid', '>', '0')
            ->whereBetweenTime('o.pay_time', $todayS, $todayE)
            ->count('o.order_id');

        //今日下单人数
        $today_user_pay_nums = Db::table('shop_order_info')->alias('o')
            ->join('shop_order_goods og', 'o.order_id = og.order_id')
            ->where('og.roomid', '>', '0')
            ->whereBetweenTime('o.pay_time', $todayS, $todayE)
            ->group('o.user_id')
            ->count('o.order_id');

        // 今日直播观众
        $today_user_nums = $this->Model->whereBetweenTime('end_time', $todayS, $todayE)
            ->sum('nums');

        $all_data = [
            'all_live_num'=> $this->Model->count('id'),
            'all_live_money'=> $all_live_money,
            'today_user_nums'=> $today_user_nums,
            'today_order_nums'=> $today_order_nums,
            'today_pay_money'=>$today_pay_money,
            'today_user_pay_nums'=> $today_user_pay_nums,
        ];

        $seven_days = [];
        for ($i = 6; $i >= 0; $i--) {
            $seven_days[] = date("Y-m-d",strtotime("-{$i} day"));
        }
        $seven_days_data = [];
        for ($i = 6; $i >= 0; $i--) {

            list($start, $end) = Time::daysAgoStartAndEnd($i);
            $money = Db::table('shop_order_info')->alias('o')
                ->join('shop_order_goods og', 'o.order_id = og.order_id')
                ->where('og.roomid', '>', '0')
                ->whereBetweenTime('o.pay_time', $start, $end)
                ->sum('o.order_amount');

            $seven_days_data[6 - $i][] = intval($money);
        }

        $this->assign('start_day',$seven_days[0]);
        $this->assign('end_day',$seven_days[6]);
        $this->assign('seven_days',json_encode($seven_days));
        $this->assign('seven_days_data',json_encode($seven_days_data));
        $this->assign('all_data',$all_data);
        return $this->fetch();
    }
}
